<template>
    <div class="weui-cells weui-cells_form">
        <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">项目名称</label></div>
            <div class="weui-cell__bd">
                <input v-model='newItem.name' maxlength="20" class="weui-input" type="text" placeholder="必填">
            </div>
        </div>
    </div>
    <div class="weui-cells">
        <a class="weui-cell weui-cell_access" href="javascript:;" @click="selectStartTime()">
            <div class="weui-cell__bd">
                <p><span class="title">开始时间</span>{{start_time}}</p>
            </div>
            <div class="weui-cell__ft"></div>
        </a>
        <a class="weui-cell weui-cell_access" href="javascript:;" @click="selectEndTime()">
            <div class="weui-cell__bd">
                <p><span class="title">结束时间</span><span v-if="end_time" :value="end_time">{{end_time}}</span><span v-else class="placeholder">必填</span></p>
            </div>
            <div class="weui-cell__ft"></div>
        </a>
    </div>
    <div class="weui-cells">
        <a  @click.prevent="setTeam" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p>
                    <span class="title">项目归属</span>
                    <span v-if="!newItem.teamName" class="placeholder">必填</span>
                    <span :value="newItem.teamId" v-else >{{newItem.teamName | strEllipsis}}</span>
                </p>
            </div> 
            <div  class="weui-cell__ft" ></div>
        </a>
        <a @click.prevent="setType" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p><span class="title">项目类型</span><span v-if="newItem.typeName" :value="newItem.typeId">{{newItem.typeName}}</span><span v-else class="placeholder">必填</span></p>
            </div>
            <div class="weui-cell__ft" ></div>
        </a>
         <a @click.prevent="setCity" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p><span class="title">项目城市</span><span v-if="newItem.city_name" :value="newItem.typeId">{{newItem.city_name}}</span><span v-else class="placeholder">必填</span></p>
            </div>
            <div class="weui-cell__ft" ></div>
        </a>

    </div>
    <div class="weui-cells">
        <a @click.prevent="setCooperateEnterprise" class="weui-cell weui-cell_access">
            <div class="weui-cell__bd">
                <p><span class="title">合作企业</span><span v-if="newItem.relate_team_name" :value="newItem.relate_team_id">{{newItem.relate_team_name}}</span><span v-else class="placeholder">选填</span></p>
            </div>
            <div class="weui-cell__ft" ></div>
        </a>
    </div>
</template>

<script>
    /**
     *  引入工具类库 或 Native API
     *  example : import widget from 'gapi/widget'
     */
    import userCenterApi from 'clientApi/userCenterApi'
    import widget from 'gapi/widget.js'
    import commonPage from 'clientApi/commonPage'
    import * as util from 'js/util.js'
    import clientInfo from 'gapi/clientInfo'
    import clientUi from 'gapi/clientUi.js'
    import cache from 'gapi/cache'
    import teamApi from 'clientApi/teamApi.js'
    import KCApiApp from 'clientApi/KCApiApp.js'


    /**
     *  引入组件 以及 组件接口(Action)
     *  example : import Somecomponents from 'components/Somecomponents/Somecomponents'
     */

    /**
     *  组件实例对象
     */
    export default {
        components: {

        },
        filters : {
            strEllipsis : function(str) {
                if (str.length > 10) {
                    return str.substring(0, 10) + '...'
                } else {
                    return str;
                }
            }
        },
        data: function(){
            return{
                hasTeams: false,//项目团队没有隐藏 项目归属 (备注： 创建项目之后分配一个默认团队, 用于当还没有项目的时候)  //fixme
                newItem:{
                    name: '',
                    teamName: '',
                    team_id: '',
                    project_id: '',
                    typeName: '',
                    typeId: '',
                    city_id: '',
                    city_name: '',
                    relate_team_id: '',
                    relate_team_name: '',
                },
                teamList: {
                    data1: [], //用于滚轮
                    data: [] //用于name -> id
                },
                userId: '',
                start_time:'',
                end_time:''
            }
        },
        vuex: {
            getters: {

            },
            actions: {

            }
        },
        methods: {
            /**
             * 初始化
             * @method init
             * @public
             * @return {Null} void
             */
            init (){
              //使用默认企业  获取企业列表后获取默认企业  默认选中
                this.getTeamList()
                let date = new Date()
                let y = date.getFullYear()
                let m = date.getMonth() < 9 ? '0' + (date.getMonth()+1) : (date.getMonth()+1)
                let d = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()
                let today = y + '-' + m + '-' + d
                this.start_time = today


            },
            selectStartTime(){
                var self = this; 
                let date = new Date()
                let currentDate = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()
                let maxDate = this.end_time?this.end_time:'3000-12-12'
                KCApiApp.showDatePicker(
                        currentDate,//  最小时间
                        maxDate,//  最大时间
                        self.start_time, //默认时间
                        (data)=>{    
                            self.start_time = data.SelectedDate
                        })
            },
            selectEndTime(){
                var self = this;
                let date = new Date()
                let currentDate = this.start_time
                let maxDate = (date.getFullYear()+1)+"-"+(date.getMonth()+1)+"-"+date.getDate()
                KCApiApp.showDatePicker(
                        currentDate,//  最小时间
                        maxDate,//  最大时间
                        this.end_time, //默认时间
                        (data)=>{                  //回调方法
                            this.end_time = data.SelectedDate
                        })
            },
            //获取企业列表
            getTeamList (){
              util.ajax({
                    url:'/team/list/simple',
                    type:'GET',
                    data:{
                      team_id: 0,//默认为0
                      project_id : 0//默认为0
                    },
                    timeout:10000,
                    success:(result) => {
                        // alert(JSON.stringify(result))
                        if(result.errno == 0){
                            if (result.data.length > 0) {
                                this.hasTeams = true
                                this.teamList.data = result.data

                                //获取默认企业
                                this.getDefaultTeam()
                            } 
                            // else {
                            //     let self = this;
                            //     this.getUserRealName(function (realName) {
                            //         self.teamList.data1.push(`${realName}的团队`)
                            //     });
                            // }
                            result.data.forEach( item => {
                                this.teamList.data1.push(item.team_name)
                            })
                        }
                    },
                    error: (xhr, status) => {
                        // error
                        console.log(xhr)
                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            getDefaultTeam(){
                util.ajax({
                    url:'/user/info',
                    type:'GET',
                    data:{
                        team_id: 0,//默认为0
                        project_id : 0//默认为0
                    },
                    timeout:10000,
                    success:(result) => {
                        console.log(result)
                        if(result.errno == 0){
                            if(result.data.team_id != ''){
                                console.log(result.data.team_id)
                                console.log(result.data.team_name)
                                this.newItem.teamName = result.data.team_name
                                this.newItem.teamId = result.data.team_id
                            }
                        }
                    },
                    error: (xhr, status) => {
                        // error
                        console.log(xhr)
                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            setTeam (){
                let nData = {
                    data1: this.teamList.data1
                }
                let index = 0
                if(this.newItem.teamName){
                    index = this.teamList.data1.indexOf(this.newItem.teamName)
                    // console.log(index)
                }
                
                clientUi.showPicker(nData, [index], '', (data) => {
                    // console.log(data)
                    if(data.data1 !== undefined){
                        this.newItem.teamName = this.teamList.data1[data.data1]
                        this.teamList.data.forEach((item) => {//根据name 查找id
                            if(item.team_name == this.newItem.teamName) {
                                this.newItem.teamId = item.team_id
                                return;
                            }
                        })
                    }
                    
                })
            },
            setType (){
                if(this.newItem.typeId){
                    cache.setMemoryCache('projectTypeId', {val : this.newItem.typeId})
                } else {
                    cache.setMemoryCache('projectTypeId', null);
                }
                window.location.href='dmsaas://ProjectType'
            },
            setCooperateEnterprise (){

                window.location.href="dmsaas://CooperateEnterprise?urdData=" + encodeURIComponent(`team_id=${this.newItem.teamId}&relate_team_id=${this.newItem.relate_team_id}&relate_team_name=${this.newItem.relate_team_name}&source=new`)
            },
            updateProType (data){
                console.log(data)
                let key = data.key
                let value = data.value
                switch(key){
                    case 'proType':
                        this.newItem.typeId = value.typeId
                        this.newItem.typeName = value.typeName
                        break
                    case 'city_data':
                        this.newItem.city_id = value.city_id
                        this.newItem.city_name = value.city_name
                        break
                    case 'relate_team_info':
                        this.newItem.relate_team_id = value.team_id ? value.team_id : ''
                        this.newItem.relate_team_name = value.team_name ? value.team_name : ''
                        break
                }
            },
            getUserRealName (cb) {
                util.ajax({
                    url:'/project/get/realname',
                    type:'GET',
                    data:{
                        team_id: 0,//默认为0
                        project_id : 0//默认为0
                    },
                    timeout:10000,
                    beforeSend: () => {

                    },
                    success:(result) => {
                        if(result.errno == 0){
                            cb && cb(result.data.real_name);
                        }
                    },
                    error: (xhr, status) => {
                        // error
                        console.log(xhr)
                    },
                    complete: () => {

                    },
                    noNetwork: () => {
                        // 无网络的回调
                        widget.toast('网络连接失败，请检查网络')
                    }
                })
            },
            doSubmit (){ //创建项目action
                //校验
                if (!this.newItem.name){
                    widget.toast('请填写项目名称')
                    return
                } 
                else if (!this.newItem.teamId && this.hasTeams){
                    widget.toast('请选择项目归属')
                    return
                } 
                else if (!this.newItem.typeId){
                    widget.toast('请选择项目类型')
                    return
                }
                else if(!this.start_time){
                    widget.toast('请选择项目开始时间')
                    return 
                }
                else if(!this.end_time){
                    widget.toast('请选择项目结束时间')
                    return
                }
                else if(!this.newItem.city_name){
                    widget.toast('请选择项目城市')
                    return
                }
                let _data = {
                    team_id: this.newItem.teamId,//新建项目归属在默认企业下
                    project_name: this.newItem.name, 
                    project_type: this.newItem.typeId,
                    start_date: this.start_time,
                    end_date: this.end_time,
                    city_id: this.newItem.city_id,
                    city_name: this.newItem.city_name
                }
                if(this.newItem.relate_team_id){
                    _data.relate_team_id = this.newItem.relate_team_id
                }
                if (this.doSubmitLock) {
                    return
                }
                this.doSubmitLock = true;
                console.log(_data)
                util.ajax({
                      url:'/project/create',
                      type:'POST',
                      data: _data,
                      timeout:10000,
                      beforeSend: () => {

                      },
                      success:(result) => {
                        console.log(result)
                        if(result.errno == 0){
                            // if (!this.newItem.teamId) {
                            //     teamApi.updateTeam();
                            // }
                            //埋点
                            let statisticsLog_data = {
                                event_id: '创建项目页-完成',
                                // event_label: data.event_label,(预留，现在不用传此参数)
                                event_param: {
                                    ca_from: 'done',
                                    project_id: result.data.project_id,
                                }
                            }
                            // alert(JSON.stringify(statisticsLog_data))
                            KCApiApp.statisticsLog(statisticsLog_data)


                            widget.toast('创建成功')
                            // let urdData = `projectName=${encodeURIComponent(_data.project_name)}&teamId=${result.data.team_id}&projectId=${result.data.project_id}&memberCount=1&unreadmsg=1`;
                            // console.log(urdData)
                            // window.location.href = `dmsaas://ProjectDetail?${urdData}`;
                            let encodeStr = `project_name=${encodeURIComponent(_data.project_name)}&team_id=${result.data.team_id}&project_id=${result.data.project_id}`
                            window.location.href = `dmsaas://ProjectDetail?${encodeStr}`
                            // let encodeStr = encodeURIComponent(`project_name=${_data.project_name}&team_id=${result.data.team_id}&project_id=${result.data.project_id}`)
                            // window.location.href = `dmsaas://ProjectDetail?urdData=${encodeStr}`
                        }else if(result.errno == 11042){
                            widget.toast('项目名称不能包含表情')
                            this.doSubmitLock = false
                        }else{
                            widget.toast(result.errmsg)
                            this.doSubmitLock = false
                        }
                          
                      },
                      error: (xhr, status) => {
                          console.log(xhr)
                          this.doSubmitLock = false
                      },
                      noNetwork: () => {
                          // 无网络的回调
                          widget.toast('网络连接失败，请检查网络')
                          this.doSubmitLock = false;
                      }
                  })
            },
            //设置城市
            setCity (){
                //增加选中状态时使用
                // let encodeStr = encodeURIComponent(`city_id=${this.newItem.city_id}&city_name=${this.newItem.city_name}`)
                let encodeStr = `city_id=${this.newItem.city_id}&city_name=` + encodeURIComponent(`${this.newItem.city_name}`)
                window.location.href = `dmsaas://SelectCityList?${encodeStr}`
            }
        },
        created(){
            this.init();
            window.loadData = this.updateProType
            window.submit = this.submit
        },
        ready(){
            //获取userid
            // userCenterApi.getUserInfo(data => {
            //     this.userId = data.userId
            // })
            //控制header 右侧显示'完成'定义rightAction
            commonPage.updateTitleBar({
                leftDisplay: false,
                rightDisplay: true,
                rightText: '完成',
                rightAction: 'doSubmit'
            })
            window.doSubmit = this.doSubmit
        }

    }


</script>

<!-- CSS 样式 -->
<style src="../../node_modules/weui/dist/style/weui.css"></style>
<style src="../../static/css/common.css"></style>
